package com.dmall.scf.utils.express;

import com.dmall.scf.constants.RegularsConstants;
import com.dmall.scf.utils.express.operator.OperatorSum;
import com.google.common.collect.Sets;
import com.ql.util.express.DefaultContext;
import com.ql.util.express.ExpressRunner;
import lombok.extern.slf4j.Slf4j;

import java.util.Set;

/**
 * QLExpress 工具类
 */
@Slf4j
public class ExpressUtils {
    private static final ExpressRunner expressRunner = new ExpressRunner(true,false);

    static {
        expressRunner.addFunction("sum", new OperatorSum("sum"));
    }

    public static ExpressRunner getExpressRunner() {
        return expressRunner;
    }

    /**
     * 检查表达式是否符合标准
     *
     * @param express 表达式
     */
    public static Boolean checkExpress(String express) {
        try {
            expressRunner.getOutVarNames(express);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 获取表达式字段ID
     * @param express
     * @return
     */
    public static Set<Long> getOutVarIds(String express) throws Exception {
        Set<Long> returnItems = Sets.newHashSet();
        try {
            String[] items = expressRunner.getOutVarNames(express);
            if(items == null || items.length == 0){
                return returnItems;
            }
            for(String item: items){
                returnItems.add(Long.parseLong(item.trim().replace(RegularsConstants.PREFIX_OF_FIELD, "")));
            }
        } catch (Exception e) {
            log.error("表达式:"+express+"解析失败", e);
            throw e;
        }
        return returnItems;
    }

    public static void main(String[] args) throws Throwable{
        DefaultContext<String, Object> defaultContext = new DefaultContext<>();
        String scoreRule = "if(a>1&&a<5)then{if(b>=5&&b<=10)then{2000}};if(a>=5&&a<=15)then{if(b>=5&&b<=10)then{2000}};";
        defaultContext.put("a", 3);
        defaultContext.put("b", 7);
        System.out.println(String.valueOf(ExpressUtils.getExpressRunner().execute(scoreRule, defaultContext, null, true, false)));
    }

}
